package com.wxl.common.http

import android.text.TextUtils
import com.alibaba.fastjson.JSONObject
import com.wxl.common.base.DataBean
import com.wxl.common.util.Loog
import com.wxl.common.util.Toll
import java.lang.reflect.ParameterizedType

/**
 * create file time : 2021/2/22
 * create user : wxl
 * subscribe :
 */
@Suppress("UNCHECKED_CAST", "JAVA_CLASS_ON_COMPANION")
abstract class HttpCallback<T> : AbsHttpCallback() {

    override fun success(data: DataBean) {
        if (data.code == 0 && !TextUtils.isEmpty(data.data)) {
            try {
                val dataType = findDataType()
                if(TextUtils.equals(dataType.toString(), String::class.java.name)){
                    loadDataSuccess(data.data as T)
                } else if(data.data.startsWith("[") && data.data.endsWith("]")){
                    val array = JSONObject.parseArray(data.data, dataType) as ArrayList<T>
                    loadDataSuccess(array)
                } else if(data.data.startsWith("{") && data.data.endsWith("}")) {
                    val obj = JSONObject.parseObject(data.data, dataType)
                    loadDataSuccess(obj)
                } else {
                    loadDataSuccess(data.data as T)
                }
            } catch (e:Exception){
                Loog.e(e.message.toString())
                if (isShowErrorMsg()) {
                    Toll.toll("服务器返回数据错误")
                }
                error(e)
            }
        } else {
            if (isShowErrorMsg()) {
                Toll.toll(data.msg)
            }
            error(Exception(data.msg))
        }
    }


    open fun isShowErrorMsg(): Boolean {
        return true
    }

    override fun error(e: Throwable) {
        super.error(e)
        loadDataFailed(e)
    }

    open fun loadDataSuccess(data:T){}

    open fun loadDataSuccess(datas:ArrayList<T>){}

    open fun loadDataFailed(e: Throwable){}

    protected open fun findDataType(): Class<T> {
        val superclass = javaClass.genericSuperclass
        if (superclass is ParameterizedType) {
            val arrayOfTypes = superclass.actualTypeArguments
            return arrayOfTypes[0] as Class<T>
        }
        return String::class.java as Class<T>
    }
}